<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row :gutter="40">
        <el-col :span="6">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入内容"
            clearable
            @keyup.enter.native="handleFilter"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click.native="handleFilter"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="medium"
            @click="handleAdd"
            >新增权限</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="permsList"
        row-key="id"
        v-loading="listLoading"
        highlight-current-row
        border
        style="width: 100%"
        size="medium"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="权限名称" sortable width="300px">
          <template slot-scope="scope">
            <i
              :class="getIcon(scope.row.level)"
              :style="{ color: getColor(scope.row.level) }"
            ></i>
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="权限层级" width="120px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.level | typeFilter">{{
              scope.row.level | levelFilter
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="权限路径"
          prop="path"
        ></el-table-column>
        <el-table-column
          align="center"
          label="图标"
          prop="icon"
        ></el-table-column>
        <el-table-column align="center" label="排序" width="120px">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getPerms"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑权限' : '新建权限'"
      width="30%"
    >
      <el-form
        :model="permForm"
        :rules="permFormRules"
        ref="permFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input
            v-model="permForm.name"
            placeholder="权限名称"
            maxlength="64"
            clearable
          />
        </el-form-item>
        <el-form-item label="权限路径" prop="path">
          <el-input v-model="permForm.path" placeholder="权限路径" clearable />
        </el-form-item>
        <el-form-item label="父级权限">
          <el-cascader
            v-model="selectedKeys"
            :options="permsParentList"
            :props="props"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="权限层级" prop="level">
          <el-select
            v-model="permForm.level"
            placeholder="请选择权限层级"
            clearable
          >
            <el-option
              v-for="item in levels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="permForm.icon" placeholder="图标" clearable />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="permForm.sort" placeholder="排序" clearable />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SavePerm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { perms_list, addPerm, updatePerm, delPerm } from "@/api/perms";
import { getParentsPath } from "@/utils/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const defaultPerm = {
  id: undefined,
  name: "",
  path: "",
  parent: undefined,
  parent_path: "",
  parent_name: "",
  level: undefined,
  icon: "",
  sort: undefined,
};
const levels = [
  { value: 0, label: "一级" },
  { value: 1, label: "二级" },
  { value: 2, label: "三级" },
  { value: 3, label: "四级" },
];
const Colors = {
  0: "#409EFF",
  1: "#67C23A",
  2: "#E6A23C", //Warning
  3: "#F56C6C",
  4: "#909399",
};
const Icons = {
  0: "el-icon-menu",
  1: "el-icon-tickets",
  2: "el-icon-star-off",
  3: "el-icon-document",
  4: "el-icon-edit",
};
// arr to obj
const levelKeyValue = levels.reduce((acc, cur) => {
  acc[cur.value] = cur.label;
  return acc;
}, {});

export default {
  name: "Permission",
  filters: {
    levelFilter(level) {
      return levelKeyValue[level];
    },
    typeFilter(type) {
      const typeMap = {
        0: "",
        1: "success",
        2: "warning",
        3: "danger",
      };
      return typeMap[type];
    },
  },
  data() {
    return {
      permForm: Object.assign({}, defaultPerm),
      permFormRules: {
        name: [{ required: true, message: "请输入权限名称", trigger: "blur" }],
        path: [{ required: true, message: "请输入权限路径", trigger: "blur" }],
        level: [
          {
            required: true,
            message: "请选择权限层级",
            trigger: "blur, change",
          },
        ],
      },
      levels,
      dialogVisible: false,
      dialogType: "new",
      permsList: [],
      permsParentList: [],
      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        checkStrictly: true,
        value: "id",
        label: "name",
        children: "children",
      },
      tableKey: 0,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
      },
    };
  },
  components: {
    Pagination,
  },
  created() {
    this.getPerms();
    this.getParentPermList();
  },
  methods: {
    getPerms() {
      this.listLoading = true;
      perms_list(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.permsList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.listLoading = false;
        });
    },
    getParentPermList() {
      const query = { type: "tree" };
      perms_list(query).then((res) => {
        console.log("tree:", res);
        this.permsParentList = res;
      });
    },
    getColor(level) {
      return Colors[level];
    },
    getIcon(level) {
      return Icons[level];
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getPerms();
    },
    // 增加权限
    handleAdd() {
      this.permForm = Object.assign({}, defaultPerm);
      this.getParentPermList();
      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.permFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.permForm = Object.assign({}, scope.row);

      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(
          this.permForm.parent,
          this.permsParentList
        );
        console.log(this.selectedKeys);
        this.$refs["permFormRef"].clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该用户吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPerm(row.id);
          this.getPerms();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存操作
    async SavePerm() {
      this.$refs.permFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          this.permForm.parent_path = this.selectedKeys.join(",");
          const res = await updatePerm(this.permForm);
          console.log(isEdit, res);
          if (res) {
            this.getPerms();
          }
          // const index = this.permsList.findIndex(v => v.id === res.id);
          // this.permsList.splice(index, 1, res);
        } else {
          this.permForm.parent_path = this.selectedKeys.join(",");
          const res = await addPerm(this.permForm);
          const { id } = res;
          if (id > 0) {
            this.getPerms();
          }
        }

        const { name, path } = this.permForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>权限名称: ${name}</div>
              <div>权限路径: ${path}</div>
            `,
          type: "success",
        });
      });
    },
    handleChange(value) {
      console.log(this.selectedKeys);
      // 如果 selectedKeys 数组中的 length 大于0，证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的Id
        this.permForm.parent = this.selectedKeys[this.selectedKeys.length - 1];
        // 为当前分类的等级赋值
        this.permForm.level = this.selectedKeys.length;
      } else {
        // 父级分类的Id
        this.permForm.parent = undefined;
        // 为当前分类的等级赋值
        this.permForm.level = 0;
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select,
  .el-cascader {
    width: 100%;
  }
}
</style>